package com.wechat.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wechat.dao.AnswerDao;
import com.wechat.dao.extend.AnswerExtDao;
import com.wechat.entity.*;
import com.wechat.entity.extend.AnswerExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 *
 * @author cgc
 * @date 18/4/9
 */
@Service
public class AnswerService {

    @Value("${redpackage.minamount:1}")
    private int redPackageMinAmount;

    @Autowired
    private AnswerDao answerDao;
    @Autowired
    private AnswerExtDao answerExtDao;

    @Autowired
    private QuestionService questionService;
    @Autowired
    private AnswerDetailService answerDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserBalanceService userBalanceService;


    /**
     *
     */
    public int deleteById(Integer id) {
        return answerDao.deleteById(id);
    }

    /**
     *
     */
    public int save(Answer record) {
        return answerDao.save(record);
    }

    /**
     *
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public Answer findById(Integer id) {
        return answerDao.findById(id);
    }

    /**
     *
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public Answer findByUserQuestionId(Integer userId,Integer questionId,Integer dataState) {
        return answerDao.findByUserQuestionId(userId,questionId,dataState);
    }

    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public List<AnswerExt> findAnswerExtList(Integer userId, Integer questionId) {
        return answerExtDao.list(userId,questionId);
    }

    /**
     *
     */
    public int update(Answer record) {
        return answerDao.update(record);
    }

    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public void submitAnswers(Answer answer,String answers){
        //处理answers生成答题明细
        JSONArray array = JSONArray.parseArray(answers);
        Integer totalRight = 0;
        List<Integer> detailIds = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            Integer questionDetailId = obj.getInteger("id");
            //重复提交只保留一个
            if(detailIds.contains(questionDetailId)){
                continue;
            }
            String trueAnswer = obj.getString("answer");
            QuestionDetail questionDetail = questionService.findQuestionDetail(questionDetailId);
            Byte isRight = 0;
            if(questionDetail.getTrueAnswer().equals(trueAnswer)){
                isRight = 1;
                totalRight += 1;
            }
            AnswerDetail answerDetail = new AnswerDetail();
            answerDetail.setQuestionId(answer.getQuestionId());
            answerDetail.setUserId(answer.getUserId());
            answerDetail.setAnswerId(answer.getId());
            answerDetail.setAnswer(trueAnswer);
            answerDetail.setQuestionDetailId(questionDetailId);
            answerDetail.setIsRight(isRight);
            answerDetailService.save(answerDetail);
            detailIds.add(questionDetailId);
        }

        Question question = questionService.findQuestion(answer.getQuestionId());
        //是否已领完
        boolean check = question.getAmountStatus().equals(Question.AMOUNT_STATUS_RETURN) || question.getAmountStatus().equals(Question.AMOUNT_STATUS_TAKE)
                || question.getSurplusNumber() <= 0 || question.getAccountAmount().compareTo(new BigDecimal(0)) <= 0;

        if(check){
            Answer answer1 = new Answer();
            answer1.setId(answer.getId());
            answer1.setTotalRight(totalRight.shortValue());
            answer1.setEndTime(new Date());
            answer1.setDataState((short)1);
            answer1.setAmount(new BigDecimal(0));
            this.update(answer1);
        }else {
            //是否要扣钱发红包
            boolean isRight = false;
            //根据答对题目数获取红包金额
            BigDecimal amount = new BigDecimal(0);
            if(totalRight >= question.getTotalRight()){
                amount = this.getRedPacketAmount(question.getSurplusNumber().intValue(),question.getAccountAmount());
                isRight = amount.compareTo(new BigDecimal(0)) > 0;
            }
            Answer answer1 = new Answer();
            answer1.setId(answer.getId());
            answer1.setTotalRight(totalRight.shortValue());
            answer1.setEndTime(new Date());
            answer1.setDataState((short)1);
            answer1.setAmount(amount);
            this.update(answer1);
            if(isRight){
                //更新问题红包余额与状态
                Question question1 = new Question();
                question1.setId(question.getId());
                Integer surplusNumber = question.getSurplusNumber().intValue()-1;
                question1.setSurplusNumber(surplusNumber.shortValue());
                question1.setAccountAmount(question.getAccountAmount().subtract(amount));
                if(surplusNumber.equals(0) || surplusNumber < 0){
                    question1.setAmountStatus(Question.AMOUNT_STATUS_TAKE);
                }
                questionService.updateQuestion(question1);
                //更新红包获取人的余额和流水
                if(totalRight >= question.getTotalRight() && amount.compareTo(new BigDecimal(0)) > 0){
                    User user = userService.findById(answer.getUserId());
                    userService.updateBalance(answer.getUserId(),amount);
                    //增加账户财务流水
                    UserBalanceRecord balanceRecord = new UserBalanceRecord();
                    balanceRecord.setBalance(user.getBalance());
                    balanceRecord.setUserId(user.getId());
                    balanceRecord.setAmount(amount);
                    balanceRecord.setTitle("红包-收入");
                    balanceRecord.setRecordType(UserBalanceRecord.RECORD_TYPE_REDPACKETIN);
                    balanceRecord.setAnswerId(answer.getId());
                    balanceRecord.setQuestionId(question.getId());
                    userBalanceService.save(balanceRecord);
                }
            }
        }
    }

    /**
     * 获取红包金额 单位 元
     * @param surplusNum
     * @param surplusAmount
     * @return 单位 元
     */
    public BigDecimal getRedPacketAmount(Integer surplusNum,BigDecimal surplusAmount) {

        if(surplusNum == null || surplusNum.equals(0) || surplusAmount == null || surplusAmount.compareTo(new BigDecimal(0)) == 0){
            return new BigDecimal(0);
        }

        if(surplusNum.equals(1)){
            return surplusAmount;
        }

        int amount = surplusAmount.multiply(new BigDecimal(100)).intValue();
        int min = redPackageMinAmount;
        int max = amount-(surplusNum*redPackageMinAmount) + 1;
        Random random = new Random();
        int num = random.nextInt(max) % (max - min + 1) + min;

        return new BigDecimal(num).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_DOWN);
    }

}
